﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Threading;

using AKMII.DMRA.Common;
using AKMII.DMRA.Business.Management;
using AKMII.DMRA.Business.Service;

namespace AKMII.DMRA.Web
{
    public partial class ManageAdmin : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                AccountManager am = new AccountManager();
                List<User> admins = am.GetUsers(UserType.Administrator);
                List<NewAdminstrator> newAdmins = new List<NewAdminstrator>();
                for (int i = 0; i < admins.Count; i++)
                {
                    NewAdminstrator newAdmin = new NewAdminstrator();
                    newAdmin.Admin = admins[i];
                    newAdmins.Add(newAdmin);
                }
                Session["Admins"] = newAdmins;
                BindDataList();
            }
        }

        private void BindDataList()
        {
            int selectCount = 0;
            List<NewAdminstrator> newAdmins = new List<NewAdminstrator>();
            newAdmins = (List<NewAdminstrator>)Session["Admins"];
            List<User> admins = new List<User>();
            foreach (NewAdminstrator nmd in newAdmins)
            {
                admins.Add(nmd.Admin);
            }
            GridView1.DataSource = admins;
            GridView1.DataBind();
            for (int j = 0; j < newAdmins.Count; j++)
            {
                if (newAdmins[j].IsSelected)
                {
                    selectCount += 1;
                }
            }
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                CheckBox chbItem = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("chbItem");
                CheckBox chbActive = (CheckBox)GridView1.Rows[i].Cells[5].FindControl("chbActive");
                chbActive.Attributes.Add("onclick", "UserCheck(this);");
                if (newAdmins[GridView1.PageSize * GridView1.PageIndex + i].Admin.Status == UserStatus.Active)
                {
                    chbActive.Checked = true;
                }
                chbItem.Checked = newAdmins[GridView1.PageSize * GridView1.PageIndex + i].IsSelected;
                switch (newAdmins[GridView1.PageSize * GridView1.PageIndex + i].OperatorType)
                {
                    case OperatorStatus.Add:
                        GridView1.Rows[i].BackColor = Color.ForestGreen;
                        break;
                    case OperatorStatus.Edit:
                        GridView1.Rows[i].BackColor = Color.LightSkyBlue;
                        break;
                    case OperatorStatus.Delete:
                        GridView1.Rows[i].BackColor = Color.Red;
                        GridView1.Rows[i].Enabled = false;
                        break;
                    case OperatorStatus.Ignore:
                        GridView1.Rows[i].BackColor = Color.Orange;
                        GridView1.Rows[i].Enabled = false;
                        break;
                }
            }
            txtSelectedCount.Value = selectCount.ToString();
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.EditIndex = -1;
            List<NewAdminstrator> admins = new List<NewAdminstrator>();
            admins = (List<NewAdminstrator>)Session["Admins"];
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                CheckBox chbItem = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("chbItem");
                CheckBox chbActive = (CheckBox)GridView1.Rows[i].Cells[5].FindControl("chbActive");
                if (chbActive.Checked)
                {
                    admins[GridView1.PageSize * GridView1.PageIndex + i].Admin.Status = UserStatus.Active;
                }
                admins[GridView1.PageSize * GridView1.PageIndex + i].IsSelected = chbItem.Checked;
            }
            Session["Admins"] = admins;
            GridView1.PageIndex = e.NewPageIndex;
            BindDataList();
        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            GridView1.EditRowStyle.BackColor = Color.LightSkyBlue;
            BindDataList();
        }

        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            BindDataList();
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            string firstName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtFirstName")).Text;
            string lastName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtLastName")).Text;
            string email = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEmail")).Text;
            bool active = ((CheckBox)GridView1.Rows[e.RowIndex].FindControl("chbActive")).Checked;
            List<NewAdminstrator> admins = new List<NewAdminstrator>();
            admins = (List<NewAdminstrator>)Session["Admins"];
            admins[GridView1.PageSize * GridView1.PageIndex + e.RowIndex].OperatorType = OperatorStatus.Edit;
            admins[GridView1.PageSize * GridView1.PageIndex + e.RowIndex].Admin.Email = email;
            //newmds[GridView1.PageSize * GridView1.PageIndex + e.RowIndex].IsSelected = true;
            admins[GridView1.PageSize * GridView1.PageIndex + e.RowIndex].Admin.FirstName = firstName;
            admins[GridView1.PageSize * GridView1.PageIndex + e.RowIndex].Admin.LastName = lastName;
            if (active)
            {
                admins[GridView1.PageSize * GridView1.PageIndex + e.RowIndex].Admin.Status = UserStatus.Active;
            }
            else
            {
                admins[GridView1.PageSize * GridView1.PageIndex + e.RowIndex].Admin.Status = UserStatus.Inactive;
            }
            GridView1.EditIndex = -1;
            Session["Admins"] = admins;
            BindDataList();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            List<NewAdminstrator> admins = new List<NewAdminstrator>();
            admins = (List<NewAdminstrator>)Session["Admins"];
            for (int j = 0; j < admins.Count; j++)
            {
                if (admins[j].IsSelected)
                {
                    if (admins[j].OperatorType == OperatorStatus.Add)
                    {
                        admins[j].OperatorType = OperatorStatus.Ignore;
                    }
                    else
                    {
                        admins[j].OperatorType = OperatorStatus.Delete;
                    }
                    admins[j].IsSelected = true;
                }
            }
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                CheckBox chbItem = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("chbItem");
                if (chbItem.Checked)
                {
                    if (admins[GridView1.PageSize * GridView1.PageIndex + i].OperatorType == OperatorStatus.Add)
                    {
                        admins[GridView1.PageSize * GridView1.PageIndex + i].OperatorType = OperatorStatus.Ignore;
                    }
                    else
                    {
                        admins[GridView1.PageSize * GridView1.PageIndex + i].OperatorType = OperatorStatus.Delete;
                    }
                    admins[GridView1.PageSize * GridView1.PageIndex + i].IsSelected = true;
                }
            }
            Session["Admins"] = admins;
            GridView1.EditIndex = -1;
            BindDataList();
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            List<NewAdminstrator> admins = new List<NewAdminstrator>();
            admins = (List<NewAdminstrator>)Session["Admins"];
            User user = new User();
            user.Email = txtAddEmail.Text;
            user.Id = txtAddMDId.Text;
            user.FirstName = txtAddFirstName.Text;
            user.LastName = txtAddLastName.Text;
            string password = Utility.BuildPassword(8);
            user.Password = FormsAuthentication.HashPasswordForStoringInConfigFile(password,
                Constants.EncryptSetting);
            user.Type = UserType.Administrator;
            NewAdminstrator admin = new NewAdminstrator();
            admin.OperatorType = OperatorStatus.Add;
            admin.Admin = user;
            admin.Password = password;
            admins.Add(admin);
            Session["Admins"] = admins;
            GridView1.EditIndex = -1;
            BindDataList();
            txtAddEmail.Text = string.Empty;
            txtAddFirstName.Text = string.Empty;
            txtAddLastName.Text = string.Empty;
            txtAddMDId.Text = string.Empty;
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            AccountManager am = new AccountManager();
            List<User> users = am.GetUsers(UserType.Administrator);
            List<NewAdminstrator> admins = new List<NewAdminstrator>();
            for (int i = 0; i < users.Count; i++)
            {
                NewAdminstrator admin = new NewAdminstrator();
                admin.Admin = users[i];
                admins.Add(admin);
            }
            Session["Admins"] = admins;
            GridView1.EditIndex = -1;
            BindDataList();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            List<NewAdminstrator> admins = new List<NewAdminstrator>();
            admins = (List<NewAdminstrator>)Session["Admins"];
            AccountManager am = new AccountManager();
            for (int i = 0; i < admins.Count; i++)
            {
                switch (admins[i].OperatorType)
                {
                    case OperatorStatus.Add:
                        if (am.CreateUser(admins[i].Admin))
                        {
                            Mail mail = new Mail();
                            mail.Subject = "New Account Created";
                            mail.Content = "Your Id is " + admins[i].Admin.Id + " and your password is " + admins[i].Password;
                            mail.Recipients = new List<string>() { admins[i].Admin.Email };

                            Thread thread = new Thread(new ParameterizedThreadStart(SendPassword));
                            thread.Start(mail);

                            Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "isAdded", "<script type='text/javascript'>alert('Congratulations, you have added successfully! ');</script>");
                        }
                        else
                        {
                            Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "Addfailed", "<script type='text/javascript'>alert('Sorry, you have failed! ');</script>");
                        }
                        break;
                    case OperatorStatus.Delete:
                        if (am.RemoveUserById(admins[i].Admin.Id))
                        {
                            Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "isDelete", "<script type='text/javascript'>alert('Congratulations, you have deleted successfully! ');</script>");
                        }
                        else
                        {
                            Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "deletefailed", "<script type='text/javascript'>alert('Sorry, you have failed! ');</script>");
                        }
                        break;
                    case OperatorStatus.Edit:
                        if (am.UpdateUser(admins[i].Admin))
                        {
                            Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "isEdited", "<script type='text/javascript'>alert('Congratulations, you have edited successfully! ');</script>");
                        }
                        else
                        {
                            Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "Editfailed", "<script type='text/javascript'>alert('Sorry, you have failed! ');</script>");
                        }
                        break;
                    case OperatorStatus.Ignore:
                        break;
                }
            }

            admins.Clear();
            List<User> users = am.GetUsers(UserType.Administrator);
            for (int i = 0; i < users.Count; i++)
            {
                NewAdminstrator admin = new NewAdminstrator();
                admin.Admin = users[i];
                admins.Add(admin);
            }
            Session["Admins"] = admins;
            GridView1.EditIndex = -1;
            BindDataList();
        }

        protected void SendPassword(object o)
        {
            Mail mail = o as Mail;
            if (mail != null)
            {
                CommonUtility.SendMail(mail);
            }
        }
    }
}
